<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import resize from './mixins/resize'
import echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme

export default {
  mixins:[resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "350px",
    },
    autoResize: {
      type: Boolean,
      default: true,
    },
    chartData: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val);
      },
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, "macarons");
      this.setOptions(this.chartData);
    },
    setOptions(chartData = {}) {
      let series = [];
      let legend = {data:[]};
      for (const key in chartData) {
        let color = `#${Math.ceil(Math.random() * 999999)}`
        legend.data.push(key)
        series.push({
          name: key,
          itemStyle: {
            normal: {
              color,
              lineStyle: {
                color,
                width: 2,
              },
            },
          },
          smooth: false,
          type: "line",
          data: chartData[key],
          animationDuration: 2800,
          animationEasing: "cubicInOut",
        });
      }
      this.chart.setOption({
        // 直角坐标系 grid 中的 x 轴
        xAxis: {
          data: ["一月", "二月", "三月", "四月", "五月", "六月", "七月"], //类目数据
          boundaryGap: false, //坐标轴两边留白策略
          axisTick: {
            show: false, //x轴刻度隐藏
          },
        },
        // 直角坐标系内绘图网格
        grid: {
          left: 10,
          right: 10,
          bottom: 20,
          top: 30,
          containLabel: true, //grid区域是否包含坐标轴的刻度标签。
        },
        // 提示框组件。
        tooltip: {
          trigger: "axis", //触发类型。
          axisPointer: {
            //坐标轴指示器配置项。y
            type: "cross",
          },
          padding: [5, 10],
        },
        // 直角坐标系 grid 中的 y 轴
        yAxis: {
          axisTick: {
            show: false, //x轴刻度隐藏
          },
        },
        // 图例组件展现了不同系列的标记(symbol)，颜色和名字
        legend,
        series,
      });
    },
  },
};
</script>